let utils = require("./utils.js");
utils.init();
if (!requestScreenCapture(true)) {
    toast("请求截图失败");
    exit();
};
let 图片相似度 = 0.83;
let 自己牌区 = [100, 630, 2000, 275];
let 左侧出牌区 = [370, 230, 800, 260];
let 右侧出牌区 = [1170, 230, 800, 260];
let 左侧手牌数区 = [290, 430, 70, 90];
let 右侧手牌数区 = [1980, 430, 70, 90];
let findState, left, right, 模式,imageCapture;
//设置对方剩余牌悬浮框,比较该区域是否同上一次相同,(可以二值化,将白色转为黑色来达到本地识别剩余数字),如果不同的话,延迟500ms后识别出牌区.
let keys = ["大", "小", "2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3"]
let 斗地主模式 = {
    "大": 1,
    "小": 1,
    "2": 4,
    "A": 4,
    "K": 4,
    "Q": 4,
    "J": 4,
    "10": 4,
    "9": 4,
    "8": 4,
    "7": 4,
    "6": 4,
    "5": 4,
    "4": 4,
    "3": 4
}
let 跑得快模式 = {
    "大": 0,
    "小": 0,
    "2": 1,
    "A": 3,
    "K": 4,
    "Q": 4,
    "J": 4,
    "10": 4,
    "9": 4,
    "8": 4,
    "7": 4,
    "6": 4,
    "5": 4,
    "4": 4,
    "3": 4
}
let 自己牌图片 = [
    images.read("./res/self_大王.png"),
    images.read("./res/self_小王.png"),
    images.read("./res/self_2.png"),
    images.read("./res/self_A.png"),
    images.read("./res/self_K.png"),
    images.read("./res/self_Q.png"),
    images.read("./res/self_J.png"),
    images.read("./res/self_10.png"),
    images.read("./res/self_9.png"),
    images.read("./res/self_8.png"),
    images.read("./res/self_7.png"),
    images.read("./res/self_6.png"),
    images.read("./res/self_5.png"),
    images.read("./res/self_4.png"),
    images.read("./res/self_3.png")
]
let 别人牌图片 = [
    images.read("./res/大王.png"),
    images.read("./res/小王.png"),
    images.read("./res/2.png"),
    images.read("./res/A.png"),
    images.read("./res/K.png"),
    images.read("./res/Q.png"),
    images.read("./res/J.png"),
    images.read("./res/10.png"),
    images.read("./res/9.png"),
    images.read("./res/8.png"),
    images.read("./res/7.png"),
    images.read("./res/6.png"),
    images.read("./res/5.png"),
    images.read("./res/4.png"),
    images.read("./res/3.png")
];
let 剩余牌数图片 = [
    images.read("./res/剩余0.png"),
    images.read("./res/剩余1.png"),
    images.read("./res/剩余2.png"),
    images.read("./res/剩余3.png"),
    images.read("./res/剩余4.png"),
    images.read("./res/剩余5.png"),
    images.read("./res/剩余6.png"),
    images.read("./res/剩余7.png"),
    images.read("./res/剩余8.png"),
    images.read("./res/剩余9.png"),
    images.read("./res/剩余10.png"),
    images.read("./res/剩余11.png"),
    images.read("./res/剩余12.png"),
    images.read("./res/剩余13.png"),
    images.read("./res/剩余14.png"),
    images.read("./res/剩余15.png"),
    images.read("./res/剩余16.png"),
    images.read("./res/剩余17.png"),
    images.read("./res/剩余18.png"),
    images.read("./res/剩余19.png"),
    images.read("./res/剩余20.png"),
    images.read("./res/剩余-1.png")
]
let w, total;
function 左侧出牌(image, num) {
    找别人的牌(image, num, true);
}
function 右侧出牌(image, num) {
    找别人的牌(image, num, false);
}
function 出牌格式化(obj) {
    let str = ''
    for (let index = 0; index < 15; index++) {
        switch (obj[keys[index]]) {
            case 1:
                str += keys[index];
                break;
            case 2:
                str = str + keys[index] + keys[index];
                break;
            case 3:
                str = str + keys[index] + keys[index] + keys[index];
                break;
            case 4:
                str = str + keys[index] + keys[index] + keys[index] + keys[index];
                break;
            default:
                break;
        }
    }
    showText(str);
    return str;
}
function 找别人的牌(img, playNum, isLeft) {
    let tempObj = {};
    let result;
    let sum = 0;
    let 出牌区 = isLeft ? 左侧出牌区 : 右侧出牌区;
    for (let index = 0; index < 别人牌图片.length; index++) {
        if (index == 0 || index == 1) {
            if (images.findImage(img, 别人牌图片[index], {
                region: 出牌区,
                //threshold: 图片相似度
            })) {
                log("进来 找到大小王", index);
                tempObj[keys[index]] = 1;
                sum += 1;
            }
        } else {
            result = images.matchTemplate(img, 别人牌图片[index], {
                max: 4,
                region: 出牌区,
                threshold: 图片相似度

            });
            let matches = result.matches;
            if (result.matches.length == 0) {
                continue;
            }
            // log("别人出的牌中找到" + keys[index] + "   " + matches.length + "张")
            console.log("===============================\n", result, "\n===============================")
            for (var k = 0; k < matches.length; k++) {//去重
                for (var l = k + 1; l < matches.length; l++) {
                    if (matches[k].point.toString() == matches[l].point.toString()) {//相邻的两个点位置相同,说明同张牌找了两次
                        matches.splice(l, 1)
                        l--
                    }
                }
            }
            tempObj[keys[index]] = matches.length;
            sum += matches.length;
        }
    }
    console.log("目标出牌", playNum, '实际出牌', sum);

    if (sum != playNum) {
        imageCapture = images.captureScreen();
        找别人的牌(imageCapture, playNum, isLeft)
    } else {
        for (let key in tempObj) {
            total[key] = total[key] - tempObj[key];
        }
        出牌格式化(tempObj);
    }
}

function 找自己牌() {
    log("模式", 模式)
    total = Object.assign({}, 模式);
    if (images.findImage(imageCapture, 自己牌图片[0], { region: 自己牌区 })) {
        total['大'] = 0;
        log("自己牌找到" + keys[0] + "   1张")
    }
    if (images.findImage(imageCapture, 自己牌图片[1], { region: 自己牌区 })) {
        total['小'] = 0;
        log("自己牌找到" + keys[1] + "   1张")
    }
    let result, count;
    for (let index = 0; index < 自己牌图片.length; index++) {
        if (index == 0 || index == 1) {
            continue;
        }
        result = images.matchTemplate(imageCapture, 自己牌图片[index], {
            max: 4,
            threshold: 图片相似度,//本来0.82
            region: 自己牌区
        });
        if (result.matches.length == 0) {
            continue;
        }
        let matches = result.matches;
        // log(matches)
        for (var k = 0; k < matches.length; k++) {
            for (var l = k + 1; l < matches.length; l++) {
                if (matches[k].point.toString() == matches[l].point.toString()) {
                    matches.splice(l, 1)
                    l--
                }
            }
        }

        log("自己牌找到" + keys[index] + "   " + matches.length + "张")
        count = total[keys[index]] - matches.length;
        // total[key] = count > 0 ? count : 0;
        total[keys[index]] = count;
    }
    console.log("检测完自己牌的结果:", total)
}
function 修改剩余牌数() {
    ui.run(() => {
        w.num_da.setText("" + total["大"]);
        w.num_xiao.setText("" + total["小"]);
        w.num2.setText("" + total["2"]);;
        w.num3.setText("" + total["3"]);
        w.num4.setText("" + total["4"]);
        w.num5.setText("" + total["5"]);
        w.num6.setText("" + total["6"]);
        w.num7.setText("" + total["7"]);
        w.num8.setText("" + total["8"]);
        w.num9.setText("" + total["9"]);
        w.num10.setText("" + total["10"]);
        w.numj.setText("" + total["J"]);
        w.numq.setText("" + total["Q"]);
        w.numk.setText("" + total["K"]);
        w.numa.setText("" + total["A"]);

        if (total["大"] == 1 && total["小"] == 1) {
            w.num_da.setTextColor(colors.RED);
            w.num_xiao.setTextColor(colors.RED);
        } else {
            w.num_da.setTextColor(colors.BLACK);
            w.num_xiao.setTextColor(colors.BLACK);
        }
        w.num2.setTextColor(total["2"] == 4 ? colors.RED : colors.BLACK);
        w.num3.setTextColor(total["3"] == 4 ? colors.RED : colors.BLACK);
        w.num4.setTextColor(total["4"] == 4 ? colors.RED : colors.BLACK);
        w.num5.setTextColor(total["5"] == 4 ? colors.RED : colors.BLACK);
        w.num6.setTextColor(total["6"] == 4 ? colors.RED : colors.BLACK);
        w.num7.setTextColor(total["7"] == 4 ? colors.RED : colors.BLACK);
        w.num8.setTextColor(total["8"] == 4 ? colors.RED : colors.BLACK);
        w.num9.setTextColor(total["9"] == 4 ? colors.RED : colors.BLACK);
        w.num10.setTextColor(total["10"] == 4 ? colors.RED : colors.BLACK);
        w.numj.setTextColor(total["J"] == 4 ? colors.RED : colors.BLACK);
        w.numq.setTextColor(total["Q"] == 4 ? colors.RED : colors.BLACK);
        w.numk.setTextColor(total["K"] == 4 ? colors.RED : colors.BLACK);
        w.numa.setTextColor(total["A"] == 4 ? colors.RED : colors.BLACK);


    })
}
function 初始化界面() {
    w = floaty.window(
        <frame id='a' w="190" h='auto' bg="#aaffffff">
            <vertical >
                <horizontal id="horizontal" h='30' >
                    <vertical id='大王' w="9" layout_gravity="center">
                        <text text='大' gravity="center" textSize='9sp' textColor='black' />
                        <text id='num_da' text='1' gravity="center" textSize='9sp' textColor='black' />
                    </vertical>
                    <View bg="#30000000" w='1' />
                    <vertical id='小王' w="9" layout_gravity="center">
                        <text text='小' gravity="center" textSize='9sp' textColor='black' />
                        <text id='num_xiao' text='1' gravity="center" textSize='9sp' textColor='black' />
                    </vertical>
                    <View bg="#30000000" w='1' />
                    <vertical id='p2' w="9" layout_gravity="center">
                        <text text='2' gravity="center" textSize='9sp' textColor='black' />
                        <text id='num2' text='4' gravity="center" textSize='9sp' textColor='black' />
                    </vertical>
                    <View bg="#30000000" w='1' />

                    <vertical id='pa' w="9" layout_gravity="center">
                        <text text='A' gravity="center" textSize='9sp' textColor='black' />
                        <text id='numa' text='4' gravity="center" textSize='9sp' textColor='black' />
                    </vertical>
                    <View bg="#30000000" w='1' />
                    <vertical id='pk' w="9" layout_gravity="center">
                        <text text='K' gravity="center" textSize='9sp' textColor='black' />
                        <text id='numk' text='4' gravity="center" textSize='9sp' textColor='black' />
                    </vertical>
                    <View bg="#30000000" w='1' />
                    <vertical id='pq' w="9" layout_gravity="center">
                        <text text='Q' gravity="center" textSize='9sp' textColor='black' />
                        <text id='numq' text='4' gravity="center" textSize='9sp' textColor='black' />
                    </vertical>
                    <View bg="#30000000" w='1' />
                    <vertical id='pj' w="9" layout_gravity="center">
                        <text text='J' gravity="center" textSize='9sp' textColor='black' />
                        <text id='numj' text='4' gravity="center" textSize='9sp' textColor='black' />
                    </vertical>
                    <View bg="#30000000" w='1' />
                    <vertical id='p10' w="9" layout_gravity="center">
                        <text text='10' textSize="12sp" marginBottom="3" gravity="center" textSize='8sp' textColor='black' />
                        <text id='num10' text='4' gravity="center" textSize='9sp' textColor='black' />
                    </vertical>
                    <View bg="#30000000" w='1' />
                    <vertical id='p9' w="9" layout_gravity="center">
                        <text text='9' gravity="center" textSize='9sp' textColor='black' />
                        <text id='num9' text='4' gravity="center" textSize='9sp' textColor='black' />
                    </vertical>
                    <View bg="#30000000" w='1' />
                    <vertical id='p8' w="9" layout_gravity="center">
                        <text text='8' gravity="center" textSize='9sp' textColor='black' />
                        <text id='num8' text='4' gravity="center" textSize='9sp' textColor='black' />
                    </vertical>
                    <View bg="#30000000" w='1' />
                    <vertical id='p7' w="9" layout_gravity="center">
                        <text text='7' gravity="center" textSize='9sp' textColor='black' />
                        <text id='num7' text='4' gravity="center" textSize='9sp' textColor='black' />
                    </vertical>
                    <View bg="#30000000" w='1' />
                    <vertical id='p6' w="9" layout_gravity="center">
                        <text text='6' gravity="center" textSize='9sp' textColor='black' />
                        <text id='num6' text='4' gravity="center" textSize='9sp' textColor='black' />
                    </vertical>
                    <View bg="#30000000" w='1' />
                    <vertical id='p5' w="9" layout_gravity="center">
                        <text text='5' gravity="center" textSize='9sp' textColor='black' />
                        <text id='num5' text='4' gravity="center" textSize='9sp' textColor='black' />
                    </vertical>
                    <View bg="#30000000" w='1' />
                    <vertical id='p4' w="9" layout_gravity="center">
                        <text text='4' gravity="center" textSize='9sp' textColor='black' />
                        <text id='num4' text='4' gravity="center" textSize='9sp' textColor='black' />
                    </vertical>
                    <View bg="#30000000" w='1' />
                    <vertical id='p3' w="9" layout_gravity="center">
                        <text text='3' gravity="center" textSize='9sp' textColor='black' />
                        <text id='num3' text='4' gravity="center" textSize='9sp' textColor='black' />
                    </vertical>
                    <View bg="#30000000" w='1' />
                    <button id="btn" textSize='8sp' w="auto" text="重启" />
                </horizontal>
                <View bg="#30000000" h='1' w='*' />
                <text id='show' text='等待开始' gravity='center' textSize='9sp' />
            </vertical>
        </frame>
    )
    w.setPosition(860, 70)
    var x1, y1 = 0;//记录按键被按下时的触摸坐标
    var windowX1, windowY1;//记录按键被按下时的悬浮窗位置
    w.a.setOnTouchListener(function (view, event) {
        switch (event.getAction()) {
            case event.ACTION_DOWN:
                x1 = event.getRawX();
                y1 = event.getRawY();
                windowX1 = w.getX();
                windowY1 = w.getY();
                return true;
            case event.ACTION_MOVE:
                //移动手指时调整悬浮窗位置
                tempx = windowX1 + (event.getRawX() - x1)
                tempy = windowY1 + (event.getRawY() - y1)
                w.setPosition(tempx < 0 ? 0 : tempx, tempy < 0 ? 0 : tempy);
                return true;
            case event.ACTION_UP:
                return true;
        }
        return true;
    });
    w.btn.on("click", () => {//点击重开
        // utils.startScript("斗地主.js");
        threads.start(function name(params) {
            找自己牌();
            修改剩余牌数();
        });
    });
    w.btn.on("long_click", () => {//长按退出
        exit();
    });


}
function showText(text) {
    ui.run(() => {
        w.show.setText(text);
    });
    log(text)
}
function 使用一轮记牌器() {
    showText('开始新的一局')
    找自己牌();
    findState = true;
    while (findState) {
        sleep(200)
        imageCapture = images.captureScreen();
        if (images.findImage(imageCapture, 剩余牌数图片[21], { region: 左侧手牌数区 })) {
            findState = false;
            log('左侧出完')
            break;
        }
        for (let index = left; index >= 0; index--) {
            if (images.findImage(imageCapture, 剩余牌数图片[index], { region: 左侧手牌数区 })) {
                leftPlayNum = left - index;//左侧出牌数
                if (index == 0 || leftPlayNum < 0) {
                    findState = false;
                }
                if (leftPlayNum == 0) {
                    break;
                }

                console.log("****左侧剩余", index, "张*************");
                左侧出牌(imageCapture, leftPlayNum);
                left = index;
                break;
            }
        }
        if (images.findImage(imageCapture, 剩余牌数图片[21], { region: 右侧手牌数区 })) {
            findState = false;
            log('右侧出完')
            break;
        }
        for (let index = right; index >= 0; index--) {
            if (images.findImage(imageCapture, 剩余牌数图片[index], { region: 右侧手牌数区 })) {
                rightPlayNum = right - index;
                if (index == 0 || rightPlayNum < 0) {
                    findState = false;
                }
                if (rightPlayNum == 0) {
                    break;
                }
                console.log("*****右侧剩余", index, "张************");
                右侧出牌(imageCapture, rightPlayNum);
                right = index;
                break;
            }
        }

        修改剩余牌数();
    }
    showText("等待开始");
    sleep(10000);
}
function main() {
    初始化界面();
    模式 = 斗地主模式;
    // 模式 = 跑得快模式;
    if (模式 == 斗地主模式) {
        while (true) {
            while (btnFlag) {
                imageCapture = images.captureScreen();
                if (images.findImage(imageCapture, images.read("./res/抢地主.png"))) {
                    找自己牌();
                    修改剩余牌数();
                    showText('外面剩余牌');
                    break;//结束找地主开始按钮
                }
            }
            while (btnFlag) {
                //先找自己牌
                imageCapture = images.captureScreen();
                if (p = images.findImage(imageCapture, images.read("./res/地主标记.png"))) {
                    console.log(p);
                    if (p.y > utils.DEVICE_WIDTH / 2) {//自己地主
                        log('自己地主')
                        left = 17;
                        right = 17;
                    } else if (p.x < utils.DEVICE_HEIGH / 2) {//左侧地主
                        log('左侧地主')
                        left = 20;
                        right = 17;
                    } else if (p.x > utils.DEVICE_HEIGH / 2) {//右侧地主
                        log('右侧地主')
                        left = 17;
                        right = 20;
                    }
                    使用一轮记牌器();
                    break;//
                }
            }
        }
    } else if (模式 == 跑得快模式) {
        while (true) {
            imageCapture = images.captureScreen();
            if (images.findImage(imageCapture, images.read("./res/不加倍.png"), { region: [0, 540, 2000, 500] })) {
                left = 16;
                right = 16;
                使用一轮记牌器();
                break;//结束找地主开始按钮
            }
        }
    }
}
function start(lastTime) {
    var storage = storages.create("FirstUseTime");
    if (!storage.get("canUse")) {
        let timeStr = utils.getNetTime();
        console.log(timeStr);
        var sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        let time = sdf.parse(timeStr).getTime();
        let time1 = sdf.parse(lastTime).getTime();
        if (time1 > time) {
            toaLog("初始化成功!")
            storage.put("canUse", true);
            main()
        } else {
            toaLog("已失效,请联系作者!")
        }
    } else {
        main();
    }
}
main();


